 
<style lang="less" scoped>
.authCode {
  width: 160px;
  /deep/.el-input__inner {
    width: 160px;
  }
}
.authCode_btn {
  margin-left: 5px;
  padding: 10px 8px;
  position: relative;
}
.person_msg {
  /deep/.el-form-item{
margin-bottom:0;
  }
}
</style>
<template>
  <div class="personalCenter">
    <el-tabs type="border-card">
      <el-tab-pane label="个人信息">
        <el-form class="person_msg">
          <el-form-item label="用户名：">{{ username }}</el-form-item>
          <el-form-item label="邮箱：">{{ email }}</el-form-item>
          <el-form-item label="角色：">{{ userType }}</el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码">
        <el-form :model="changePsw" :rules="changePswRule" ref="changePswForm" label-width="100px" style="width:21.4%">
          <el-form-item prop="username" label="用户名"> <el-input type="email" v-model="username" placeholder="请输入邮箱" disabled></el-input></el-form-item>
          <el-form-item prop="email" label="邮箱"> <el-input type="email" v-model="changePsw.email" placeholder="请输入邮箱"></el-input></el-form-item>
          <el-form-item label="验证码:" prop="authCode">
            <el-input type="text" v-model.trim="changePsw.authCode" placeholder="请输入验证码" class="authCode"></el-input>
            <el-button type="primary" class="authCode_btn" :disabled="changePsw.authCodeBtnStatus" @click.prevent="getauthCodeHandler_psw('changePswForm')">{{ changePsw.authCodeTxt }}</el-button>
          </el-form-item>
          <el-form-item prop="password" label="新密码">
            <el-input type="password" :show-password="true" v-model="changePsw.password" maxlength="16" placeholder="请输入大于6位数字和字母组合的密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPsw" label="确认新密码">
            <el-input type="password" :show-password="true" v-model="changePsw.checkPsw" placeholder="请输入确认密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="changePswHandler('changePswForm')" :disabled="changePsw_loading"><i :class="{'el-icon-loading':changePsw_loading}"></i> 提交</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- <el-tab-pane label="修改邮箱" disabled>
        <el-form :model="changeEmail" :rules="changeEmailwRule" ref="changeEmailForm" label-width="100px" style="width:21.4%">
          <el-form-item
            prop="oldEmail"
            label="旧邮箱"
            ref="oldEmail"
            :rules="[
            { required: true, message: '请输入邮箱地址'},
            {
              type: 'email',
              message: '请输入正确的邮箱地址'
            }]"
          >
            <el-input type="email" v-model="changeEmail.oldEmail" placeholder="请输入旧邮箱"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="authCode">
            <el-input type="text" v-model.trim="changeEmail.authCode" placeholder="请输入验证码" class="authCode"></el-input>
            <el-button type="primary" class="authCode_btn" :disabled="changeEmail.authCodeBtnStatus" @click="getauthCodeHandler('oldEmail')">{{ changeEmail.authCodeTxt }}</el-button>
          </el-form-item>
          <el-form-item prop="newEmail" label="确认新邮箱">
            <el-input type="email" v-model="changeEmail.newEmail" placeholder="请输入确认邮箱"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="changeEmailHandler('changeEmailForm')" :disabled="changeEmail_loading" ><i :class="{'el-icon-loading':changeEmail_loading}"></i>提交</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane> -->
    </el-tabs>
  </div>
</template>
<script>
import { isUser, isEmail, login, getAuthCode, resetpassword } from "@/api/user"
import { mapState, mapMutations } from "vuex"
import cookies from "js-cookie"
import { getUser } from '@/utils/auth'
// import { mapState, mapMutations, mapGetters } from "vuex"
export default {
  name: "personalCenter",
  data() {
    let validatePsw1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"))
      } else if (value !== this.changePsw.password) {
        callback(new Error("两次输入密码不一致!"))
      } else {
        callback()
      }
    }
    return {
      // personMsg: {
      //     username: "",
      //     email: ""
      // },
      changePsw_loading: false,
      changeEmail_loading: false,
      changePsw: {
        email: "",
        authCode: "",
        password: "",
        checkPsw: "",
        authCodeTxt: "获取验证码",
        authCodeBtnStatus: false,
        authCodeTime: 60,
      },
      changePswRule: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        authCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            message: "请输入大于6位数字和字母组合的密码",
            trigger: "blur",
          },
        ],
        checkPsw: [{required: true, validator: validatePsw1, trigger: "blur" }],
      },

      // -----------------------修改邮箱---------------------------------
      // changeEmail: {
      //   oldEmail: "",
      //   newEmail: "",
      //   checkEmail: "",
      //   authCode: "",
      //   authCodeBtnStatus: false,
      //   authCodeTime: 60,
      //   authCodeTxt: "获取验证码",
      //   authCode_disabledTxt: "后重新获取",
      // },
      // changeEmailwRule: {
      //   oldEmail: [
      //     { required: true, message: "请输入邮箱地址", trigger: "blur" },
      //     {
      //       type: "email",
      //       message: "请输入正确的邮箱地址",
      //       trigger: ["blur", "change"],
      //     },
      //   ],
      //   authCode: [
      //     { required: true, message: "验证码不能为空", trigger: "blur" },
      //   ],
      //   newEmail: [
      //     { required: true, message: "请输入邮箱地址", trigger: "blur" },
      //     {
      //       type: "email",
      //       message: "请输入正确的邮箱地址",
      //       trigger: ["blur", "change"],
      //     },
      //   ],
      // },
    }
  },
  computed: {
    // ...mapState({
    //   //  changePsw: (state) => state.loginModlue.changePsw
    // }),
    username () {
     return getUser().username
    },
    email () {
      return getUser().email
    },
     userType () {
     return getUser().type === "manager" ? '超级用户' : '普通用户' 
    },
  },
  methods: {
    ...mapMutations(["setUser"]), //存储User
    loginOut() {
      this.logoutHanlder()
    },
    async logoutHanlder() {
      await this.$store.dispatch("logout")
      this.$router.push("/")
    },
    // 倒计时

    authCodeHandler(x, y) {
      let _this = this,
        updatedKey = x,
        timeDecrease = x[y]
      let timer = setInterval(() => {
        timeDecrease--
        if (!timeDecrease <= 0) {
          this.$set(updatedKey, "authCodeTxt", timeDecrease + "s后重新获取")
          this.$set(updatedKey, "authCodeBtnStatus", true)
        } else {
          clearInterval(timer)
          this.$set(updatedKey, "authCodeTxt", "获取验证码")
          this.$set(updatedKey, "authCodeBtnStatus", false)
        }
      }, 1000)
      new Promise((resolved) => {
        if (timeDecrease != 58) resolved()
      }).then(() => {
        _this.$message({
          message: "验证码已发送至邮箱，请注意查收",
          type: "success",
          duration: 5 * 1000,
        })
      })
    },

// 修改密码-发送验证码
    getauthCodeHandler_psw(changePswRule) {
      this.$refs[changePswRule].validateField("email", (validEmail) => {
        if (!validEmail) {
           let param = new FormData()
               param.append('username', this.username)
               param.append('email', this.changePsw.email)
          getAuthCode(param).then((res) => {
            if (res.code == 0 && res.data) {
              this.authCodeHandler(this.changePsw, "authCodeTime")
            }
            // else if (res.code == 10102) {
            //   this.$message({
            //     message: "邮箱不存在",
            //     type: "warning",
            //     duration: 5 * 1000,
            //   })
            // } else {
            //   this.$message({
            //     message: "验证码发送失败，请稍后重试",
            //     type: "warning",
            //     duration: 5 * 1000,
            //   })
            // }
          })
        }
      })
    },

// 修改密码-提交

    changePswHandler(changePswRule) {
      let _this = this
      this.$refs[changePswRule].validate((valid) => {
        if (valid) {
          // 发送验证码后再次确认邮箱可用否
          isEmail(this.changePsw.email).then((res1) => {
            if (!res1.data) {
              startResetPsw()
            } 
            // else {
            //   this.$message({
            //     message: "邮箱不存在",
            //     type: "warning",
            //     duration: 3 * 1000,
            //   })
            // }
          })
          function startResetPsw() {
            let param = new FormData()
                param.append('username',_this.username)
                param.append('email',_this.changePsw.email)
                param.append('password',_this.changePsw.password)
                param.append('token',_this.changePsw.authCode)
            resetpassword(param).then((res2) => {
              if (res2.code == 0 && res2.data) {

                if (_this.changePsw_loading) {
                  return
                }
                _this.changePsw_loading = true
// 重置密码后-直接登录

                param.delete('email')
                param.delete('token')
                login(param).then((res3) => {
                    if (res3.code == 0 && res3.data && res3.data.username) {
                      _this.$message({
                        message: "密码修改成功",
                        type: "success",
                        duration: 4 * 1000,
                      })
                      _this.changePsw_loading = false
                      _this.setUser(res3.data) //存储用户信息到cookie
                      _this.$refs[changePswRule].resetFields()
                    } else {
                      // 若登录失败则退出，手动登录
                      _this.$message({
                        message: "密码修改成功，请重新登录",
                        type: "success",
                        duration: 4 * 1000,
                      })
                      _this.loginOut()
                    }
                  })
                  .finally(() => {
                    _this.changePsw_loading = false
                  })
              } else if (res2.code == 400) {
                _this.$message({
                  message: "请输入有效验证码",
                  type: "warning",
                  duration: 5 * 1000,
                })
              }
              //  else if (res2.code === 10103) {
              //   _this.$message({
              //     message: "验证码有误",
              //     type: "error",
              //     duration: 5 * 1000,
              //   })
              // } 
            })
          }
        }
      })
    },
// 获取邮箱验证码

    // getauthCodeHandler(oldEmailRule) {
    //   let _this = this
    //   let timeDecrease = this.changeEmail.authCodeTime
    //   this.$refs[oldEmailRule].validate((valid) => {
    //     if (valid) {
    //       // 发送验证码
    //       getauthCode({
    //         oldEmail: this.changeEmail.oldEmail,
    //       }).then((val) => {
    //         if (code == 200) {
    //           authCodeHandler()
    //         }
    //       })
    //     } else {
    //       _this.$message({
    //         message: "请输入正确的邮箱地址",
    //         type: "wraing",
    //         duration: 5 * 1000,
    //       })
    //     }
    //   })
    //   function authCodeHandler() {
    //     let timer = setInterval(() => {
    //       timeDecrease--
    //       if (!timeDecrease <= 0) {
    //         _this.changeEmail.authCodeTxt =
    //           timeDecrease + "s" + _this.changeEmail.authCode_disabledTxt
    //         _this.changeEmail.authCodeBtnStatus = true
    //       } else {
    //         clearInterval(timer)
    //         _this.changeEmail.authCodeTxt = "获取验证码"
    //         _this.changeEmail.authCodeBtnStatus = false
    //       }
    //     }, 1000)
    //     new Promise((resolved) => {
    //       if (timeDecrease != 58) resolved()
    //     }).then(() => {
    //       _this.$message({
    //         message: "验证码已发送至邮箱，请注意查收",
    //         type: "success",
    //         duration: 5 * 1000,
    //       })
    //     })
    //   }
    // },
    // 提交-修改邮箱
    // changeEmailHandler(changeEmailRule) {
    //   this.$refs[changeEmailRule].validate((valid) => {
    //     if (valid) {
    //       if (this.changeEmail_loading) {
    //         return
    //       }
    //       this.changeEmail_loading = true
    //       changeEmail(this.changeEmail)
    //         .then((res) => {
    //           if (res.code === 0) {
    //             // this.$message({
    //             //   message: "修改成功，请重新登录",
    //             //   type: "success",
    //             //   duration: 3 * 1000,
    //             // })
    //           }
    //         }).finally(() => {
    //           this.changeEmail_loading = false
    //         })
    //     } else {
    //       return false
    //     }
    //   })
    // },
  },
 
}
</script>
